package git.bankview.wl.common;

import java.sql.Blob;
import java.sql.Clob;
import java.util.*;
import java.io.*;

import laya.semi.process.*;

//import org.apache.log4j.Logger;

public class BinaryToStringDecorator
	implements IGenericClassActivity
{
	//private static Logger log = Logger.getLogger(BinaryToStringDecorator.class);

	public void execute(IProcessContext oCtx)
		throws Exception
	{
		String[] vPairs = oCtx.getActivityParameter().split(":");
		String oResultField = vPairs[0];
		List oResultList = (List)oCtx.getField(oResultField);
		
		for (int j = 0; j < oResultList.size(); ++j)
		{
			Map oRec = (Map)oResultList.get(j);
			for (int i = 1; i < vPairs.length; ++i)
			{
				String[] vDestSrc = vPairs[i].split("=");
				String val = null;
				// log.debug(oRec.get(vDestSrc[1]).getClass().getName());
				
				Object oSrc = oRec.get(vDestSrc[1]);
				
				if (null != oSrc)
				{
					if (oSrc.getClass().isArray())
					{
						val = new String((byte[])oSrc);
					}
					else
					{
						if (oSrc instanceof Clob)
						{
							oSrc = ((Clob)oSrc).getCharacterStream();
							//((Clob)oSrc).getCharacterStream()
							//oSrc = ((Clob)oSrc).getSubString(0, 2048);
						}
						else if (oSrc instanceof Blob)
						{
							oSrc = ((Blob)oSrc).getBinaryStream();
						}
						
						if (oSrc instanceof InputStream)
						{
							StringBuffer oDest = null;
							if (null != oSrc)
							{
								oDest = new StringBuffer();
								byte[] buff = new byte[1024];
								int nLen;
								while(0 <= (nLen = ((InputStream)oSrc).read(buff, 0, buff.length)))
								{
									oDest.append(new String(buff, 0, nLen));
								}
							}
							val = oDest.toString();
						}
						else if (oSrc instanceof Reader)
						{
							StringBuffer oDest = null;
							if (null != oSrc)
							{
								oDest = new StringBuffer();
								char[] buff = new char[1024];
								int nLen;
								while(0 <= (nLen = ((Reader)oSrc).read(buff, 0, buff.length)))
								{
									oDest.append(new String(buff, 0, nLen));
								}
							}
							val = oDest.toString();
						}
					}// end of if (oSrc.getClass().isArray())
				}// end of if (null != oSrc)
				
				oRec.put(vDestSrc[0], val);
			}
		}
	}
}
